package com.atguigu.ssyx.acl.service.impl;

import com.atguigu.ssyx.acl.mapper.PermissionMapper;
import com.atguigu.ssyx.acl.service.PermissionService;
import com.atguigu.ssyx.model.acl.Permission;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.atguigu.ssyx.acl.utils.PermissionHelper;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {
    @Override
    public Boolean removeChildById(Long id) {
//        创建idList存放要被删除的菜单内容
        List<Long> idList = new ArrayList<>();
//        idList有我们要删除菜单ID
//        根据当前菜单ID,获取当前菜单下的所有子菜单
//        如果子菜单下面还有子菜单,都要获取
//        重点:递归找当前菜单的子菜单;
        this.getAllPermissionId(id,idList);
//        设置当前菜单的ID
        idList.add(id);
//        调用方法根据多个菜单ID删除
        baseMapper.deleteBatchIds(idList);
        return true;
    }

    private void getAllPermissionId(Long id, List<Long> idList) {
//        递归找菜单下面的所有的菜单
//        第一个菜单是菜单的id,第二个是所有菜单的数值
//        根据当前ID查询当前
//        select * from permission where pid = ?
        LambdaQueryWrapper<Permission> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Permission::getPid,id);
        List<Permission> childList = baseMapper.selectList(wrapper);
//        递归查询是否还有子菜单,如果有的话就继续查询
        childList.stream().forEach(item ->{
//            封装菜单Id到
            idList.add(item.getId());
            this.getAllPermissionId(item.getId(),idList);
        });
    }

    @Override
    public List<Permission> queryAllPermission() {
//        查询出所有的菜单
        List<Permission> allPermissionList = baseMapper.selectList(null);
//        把查询出的所有的菜单转换成需求的数据格式
        List<Permission> result = PermissionHelper.buildPermission(allPermissionList);
        return result;
    }
}
